package com.weixing.mall.provider.controller.front;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.annotation.RequestLimiter;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.MemAuth;
import com.weixing.mall.provider.api.model.enums.ActTypeEnum;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.api.model.vo.ActRpcVo;
import com.weixing.mall.provider.api.model.vo.AgentRpcVo;
import com.weixing.mall.provider.api.model.vo.dto.DepotRPcVo;
import com.weixing.mall.provider.api.service.ActivityRpcService;
import com.weixing.mall.provider.api.service.DepotServiceRpc;
import com.weixing.mall.provider.manager.AgentManager;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.dto.*;
import com.weixing.mall.provider.model.enums.OrderFrontStateEnum;
import com.weixing.mall.provider.model.enums.OrderStateEnum;
import com.weixing.mall.provider.model.query.OrderSeachQuery;
import com.weixing.mall.provider.model.query.OrderVoQuery;
import com.weixing.mall.provider.model.vo.member.MemberOrderVo;
import com.weixing.mall.provider.model.vo.OrderShowVo;
import com.weixing.mall.provider.model.vo.PreOrderInfoVo;
import com.weixing.mall.provider.service.IOrderFrontService;
import com.weixing.mall.provider.service.IOrderService;
import com.weixing.mall.provider.service.IOrderTradeService;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 前端-订单相关接口
 *
 * @author gjq
 * @date 2019/9/25
 * @since 1.0
 **/
@RestController
@RequestMapping("front/order")
public class FrontOrderController extends BaseController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderTradeService orderTradeService;
    @Autowired
    private IOrderFrontService orderFrontService;
    @Autowired
    private AgentManager agentManager;
    @Autowired
    private ActivityRpcService activityRpcService;
    @Autowired
    private DepotServiceRpc depotServiceRpc;


    /**
     * 会员订单查询
     *
     * @param status 订单状态
     * @return 订单列表
     * @date 2020/5/19 18:35
     */
    @GetMapping("query/{status}")
    public Result<Page<MemberOrderVo>> getOrderList(@PathVariable OrderFrontStateEnum status) {
        Long mid = AuthUtil.getMemberExt().getMid();
        Page<MemberOrderVo> list = orderService.selectListByFrontStatus(initMpPage(), status, mid);
        return ResultUtil.success(list);
    }

    /**
     * 订单详情
     *
     * @param query 查询条件
     * @return 详情
     */
    @GetMapping("detail")
    public Result<OrderShowVo> getOrder(OrderVoQuery query) {
        OrderShowVo orderShowVo = orderService.selectOrderShowVo(query);
        return ResultUtil.success(orderShowVo);
    }

    /**
     * 查询订单
     *
     * @param query 查询条件
     * @return 订单列表
     */
    @GetMapping("search")
    public Result seachOrderList(OrderSeachQuery query) {
        query.setMemberId(AuthUtil.getMemberExt().getMid());
        IPage<MemberOrderVo> list = orderService.seachOrderList(initMpPage(), query);
        return ResultUtil.success(list);
    }

    /**
     * 会员下单:立即下单
     *
     * @param orderDto 下单参数
     * @return 下单结果
     */
    @RequestLimiter(QPS = 5D, timeout = 3000, timeunit = TimeUnit.MILLISECONDS, msg = "亲，服务器快被挤爆了，请稍后再试！")
    @PostMapping("preOrder/quick")
    @NoRepeatSubmit(leaseTime = 10)
    public Result<PreOrderInfoVo> preOrder(@RequestBody MemberPreOrderDto orderDto) {
        //  加载代理商信息
        MemAuth auth = AuthUtil.getMemberExt();
        Result<AgentRpcVo> agentCheckResult = agentManager.loadAgent(orderDto.getAgentId(), orderDto.getAgentSn(), orderDto.getAgentName(), auth);
        if (!agentCheckResult.isSuccess()) {
            return ResultUtil.error(agentCheckResult.getMsg());
        }
        Result<PreOrderInfoVo> orderInfoVoResult = orderTradeService.memberPreOrderOfQuick(orderDto, auth, agentCheckResult.getData());
        return orderInfoVoResult;
    }


    /**
     * 会员下单:秒杀
     *
     * @param orderDto 下单参数
     * @return 下单结果
     */
    @RequestLimiter(QPS = 5D, timeout = 2000, timeunit = TimeUnit.MILLISECONDS, msg = "亲，服务器快被挤爆了，请稍后再试！")
    @PostMapping("seckill")
//    @NoRepeatSubmit(leaseTime = 10)
    public Result<PreOrderInfoVo> seckill(@Validated @RequestBody MemberSeckillDto orderDto) {
        MemAuth auth = AuthUtil.getMemberExt();
        if (null != orderDto.getActId()) {
            Result<ActRpcVo> actRpcVoResult = activityRpcService.selectById(orderDto.getActId());
            if (actRpcVoResult.isSuccess()) {
                ActRpcVo actRpcVo = actRpcVoResult.getData();
                if (null != actRpcVo) {
                    ActTypeEnum actType = EnumUtil.getIEnum(ActTypeEnum.class, actRpcVo.getActIntegerType());
                    if (!ActTypeEnum.ACT_SECKILL.equals(actType)) {
                        // 会员不能下代理商活动订单
                        return ResultUtil.error("暂无下单权限");
                    }
                }
            } else {
                return ResultUtil.error("下单失败，请稍后再试");
            }
        }
        Result<AgentRpcVo> agentCheckResult = agentManager.loadAgent(orderDto.getAgentId(), orderDto.getAgentSn(), orderDto.getAgentName(), auth);
        if (!agentCheckResult.isSuccess()) {
            return ResultUtil.error(agentCheckResult.getMsg());
        }
        Result<PreOrderInfoVo> orderInfoVoResult = orderTradeService.seckill(orderDto, auth, agentCheckResult.getData());
        return orderInfoVoResult;
    }

    /**
     * 会员下单:购物车结算
     *
     * @param orderDto 下单参数
     * @return 下单结果
     */
    @RequestLimiter(QPS = 5D, timeout = 2000, timeunit = TimeUnit.MILLISECONDS, msg = "亲，服务器快被挤爆了，请稍后再试！")
    @PostMapping("preOrder/cart")
    @NoRepeatSubmit(leaseTime = 30)
    public Result<PreOrderInfoVo> preOrderOfCart(@RequestBody MemberPreOrderCartDto orderDto) {
        MemAuth auth = AuthUtil.getMemberExt();
        //  加载代理商信息
        Result<AgentRpcVo> agentCheckResult = agentManager.loadAgent(orderDto.getAgentId(), orderDto.getAgentSn(), orderDto.getAgentName(), auth);
        if (!agentCheckResult.isSuccess()) {
            return ResultUtil.error(agentCheckResult.getMsg());
        }
        PreOrderInfoVo preOrderInfoVo = orderTradeService.memberPreOrderOfCart(orderDto, auth, agentCheckResult.getData());
        return ResultUtil.success(preOrderInfoVo);
    }

    /**
     * 修改颜色尺码
     *
     * @param orderId   订单id
     * @param productId SKU id
     * @return 修改结果
     */
    @PostMapping("chgOrderGoods/{orderId}/{productId}")
    public Result chgContactOrder(@PathVariable Long orderId, @PathVariable Long productId) {
        Order order = orderService.getById(orderId);
        if (null == order) {
            return ResultUtil.error("订单不存在");
        }
        if (!OrderTypeEnum.NORMAL.getValue().equals(order.getOrderType())) {
            return ResultUtil.error("非正价订单不允许修改");
        }
        if (WhetherEnum.YES.getValue().equals(order.getIsPay())) {
            return ResultUtil.error("已付款/待审核订单不允许修改");
        }
        orderTradeService.updateOrderGoods(orderId, productId);
        return ResultUtil.success();
    }

    /**
     * 改变订单状态
     *
     * @param dto 参数
     * @return 结果
     */
    @Deprecated
    @PostMapping("changeOrderStatus")
    public Result changeOrderStatus(@Validated ChgOrderStatusDto dto) {
        orderService.changeOrderStatus(dto);
        return ResultUtil.success();
    }

    /**
     * 改变app端用户订单状态
     *
     * @param dto 参数
     * @return 结果
     */
    @Deprecated
    @PostMapping("changeFrontOrderStatus")
    public Result changeFrontOrderStatus(@Validated ChgFrontOrderStatusDto dto) {
        orderService.changeFrontOrderStatus(dto);
        return ResultUtil.success();
    }

    /**
     * 改变订单支付状态
     *
     * @param dto 参数
     * @return 结果
     */
    @PostMapping("changeOrderPayStatus")
    public Result changeOrderPayStatus(@Validated ChgOrderPayStatusDto dto) {
        orderService.changeOrderPayStatus(dto);
        return ResultUtil.success();
    }

    /**
     * 删除订单
     *
     * @param id 订单id
     * @return 结果
     */
    @PostMapping("del/{id}")
    public Result del(@PathVariable Long id) {
        Order order = orderService.getById(id);
        order.setIsDel(WhetherEnum.YES.getValue());
        orderService.updateById(order);
        return ResultUtil.success();
    }

    /**
     * 订单状态列表
     *
     * @return 状态列表
     */
    @GetMapping("orderStatus")
    public Result orderStatus() {
        return ResultUtil.success(OrderStateEnum.values());
    }

    /**
     * 扫描接受商品
     *
     * @param code 商品码
     * @return 结果
     */
    @GetMapping("scanCode/{code}")
    public Result scanCode(@PathVariable String code) {

        return ResultUtil.success(orderFrontService.scanCode(code));
    }

    /**
     * 确认收货
     *
     * @param orderId 订单id
     * @return 结果
     */
    @GetMapping("confirmOrder/{orderId}")
    @NoRepeatSubmit(leaseTime = 10)
    public Result confirmOrder(@PathVariable("orderId") Long orderId) {
        MemAuth auth = AuthUtil.getMemberExt();
        orderService.confirmOrder(auth.getMid(), orderId);
        return ResultUtil.success();
    }

    /**
     * 代理商查询：订单状态
     *
     * @return 状态
     */
    @Deprecated
    @GetMapping("orderstatusList")
    public Result orderstatusList() {
        return ResultUtil.success(OrderStateEnum.values());
    }


    /**
     * 修改订单颜色尺码，身高体重，快递方式
     *
     * @param paramDto 参数
     * @return 结果
     */
    @PostMapping("updateOrderParam")
    public Result updateOrderParam(@RequestBody OrderParamDto paramDto) {
        Long orderId = paramDto.getOrderId();
        if (null == orderId) {
            return ResultUtil.error("参数不合法");
        }

        orderTradeService.updateOrderParam(paramDto);
        return ResultUtil.success();
    }

    /**
     * 根据订单返回活动信息
     *
     * @param orderId 订单id
     * @return 活动信息
     */
    @GetMapping("actByOrderId/{orderId}")
    public Result<ActRpcVo> actByOrderId(@PathVariable Long orderId) {
        Order order = orderService.getById(orderId);
        if (null != order.getActId()) {
            ActRpcVo actRpcVo = activityRpcService.selectById(order.getActId()).getData();
            return ResultUtil.success(actRpcVo);
        } else {
            return ResultUtil.success();
        }
    }

    /**
     * 检查订单是否符合发货的要求
     *
     * @return
     */
    @GetMapping("checkOrderHasStock/{orderId}")
    public Result checkOrderHasStock(@PathVariable Long orderId) {
        Order order = orderService.getById(orderId);
        if (ObjectUtil.isNotNull(order)) {
            //换货订单直接放行，不检查
            if (order.getAfterSaleTag().equals(WhetherEnum.YES.getValue())) {
                try {
                    if (ObjectUtil.isEmpty(order.getDepotCode())) {
                        order.setDepotCode(GlobalConstant.DepotCode.OUT);
                        DepotRPcVo depotRPcVo= depotServiceRpc.getBycode(GlobalConstant.DepotCode.OUT).getData();
                        order.setDepotId(depotRPcVo.getId());
                        order.setDepotName(depotRPcVo.getDepotName());
                        orderService.updateById(order);
                    }
                } catch (Exception e) {

                }

                return ResultUtil.success();
            }

            if (ObjectUtil.isEmpty(order.getDepotCode())) {
                return ResultUtil.success(ResultCodeEnum.ERROR, "库存编码不存在");
            }
            //如果不是次品仓库或者外采仓库的，则检查
            if (!order.getDepotCode().equals(GlobalConstant.DepotCode.OUT) && !order.getDepotCode().equals(GlobalConstant.DepotCode.CP)) {
                if (ObjectUtil.isNull(order.getStockSn()) || ObjectUtil.isEmpty(order.getStockSn())) {
                    return ResultUtil.success(ResultCodeEnum.ERROR, "库存编码不存在");
                }
            }
        }

        return ResultUtil.success();

    }
}
